<script setup name="maintenanceProjectForm">
import Device from '@/views/device/components/index.vue'
import Project from './project.vue'
// vue3方法实例
const { proxy } = getCurrentInstance()

const { inspection_item_point_test_mode, inspection_item_inspection_type } = proxy.useDict(
  'inspection_item_inspection_type',
  'inspection_item_point_test_mode'
)

// 子传父
const emit = defineEmits()

// 父传子
const props = defineProps({
  isShow: {
    type: Boolean,
    default: false
  },
  //   传入数据 用于回显
  data: {
    type: Object,
    default: () => {}
  },
  // 是否禁用
  disabled: {
    type: Boolean,
    default: false
  },
  //   传入数据 弹窗标题
  title: {
    type: String,
    default: '新增'
  }
})

// 标签页字段
const activeName = ref('计划信息')

// 表单实例
const ruleFormRef = ref(null)

// 设备弹窗状态
const deviceShow = ref(false)

// 保养项目弹窗
const projectShow = ref(false)
// 周数据
const weekList = ref([
  {
    label: '周一',
    value: 1,
    key: 'week'
  },
  {
    label: '周二',
    value: 2,
    key: 'week'
  },
  {
    label: '周三',
    value: 3,
    key: 'week'
  },
  {
    label: '周四',
    value: 4,

    key: 'week'
  },
  {
    label: '周五',
    value: 5,
    key: 'week'
  },
  {
    label: '周六',
    value: 6,
    key: 'week'
  },
  {
    label: '周天',
    value: 7,
    key: 'week'
  }
])

// 月数据
const monthList = ref([
  {
    label: '一月',
    value: '01',
    key: 'month'
  },
  {
    label: '二月',
    value: '02',
    key: 'month'
  },
  {
    label: '三月',
    value: '03',
    key: 'month'
  },
  {
    label: '四月',
    value: '04',
    key: 'month'
  },
  {
    label: '五月',
    value: '05',
    key: 'month'
  },
  {
    label: '六月',
    value: '06',
    key: 'month'
  },
  {
    label: '七月',
    value: '07',
    key: 'month'
  },
  {
    label: '八月',
    value: '08',

    key: 'month'
  },
  {
    label: '九月',
    value: '09',

    key: 'month'
  },
  {
    label: '十月',
    value: '10',
    key: 'month'
  },
  {
    label: '十一月',
    value: '11',
    key: 'month'
  },
  {
    label: '十二月',
    value: '12',
    key: 'month'
  }
])

// 自定义验证
const checkAge = (rule, value, callback) => {
  if (!value) {
    return callback(new Error('请填写计划配置项'))
  }
}
// 表单字段
const ruleForm = reactive({
  planName: '', // 计划名称
  planStartTime: '', // 开始时间
  planEndTime: '', // 结束时间
  patrolItemIdStr: '', //保养项目id
  equipmentIdStr: '', //设备id
  status: '', //状态
  list: [],
  drvices: [],
  patrolItems: [],
  plannedAllocation: {
    //
    planType: 1, //
    executionInterval: '', //
    executionCycle: [], //
    executionMonth: [], //
    executionDays: [] //
  }
})

// 表单校验
const rules = reactive({
  planName: [{ required: true, message: '请填写计划名称', trigger: 'blur' }],
  plannedAllocation: [{ required: true, message: '请填写计划配置项', trigger: 'blur' }, { validator: checkAge }],
  planStartTime: [{ required: true, message: '请选择计划开始时间', trigger: 'change' }],
  planEndTime: [{ required: true, message: '请选择计划结束时间', trigger: 'change' }]
})

// 日期数据
const dayList = ref([])

// 生成日期数据
const initDay = () => {
  let i1
  for (let i = 0; i < 31; i++) {
    if (i < 9) {
      i1 = `0${i + 1}`
    } else {
      i1 = i + 1
    }
    dayList.value.push({
      label: i1,
      value: i,
      key: 'day'
    })
  }
}

initDay()

// 添加设备
const addDevice = val => {
  ruleForm.drvices = val
  deviceShow.value = false
}

// 添加保养项目
const addProject = val => {
  ruleForm.patrolItems.push(...val)
  projectShow.value = false
}

// 删除设备
const removeDevice = id => {
  const findId = ruleForm.drvices.findIndex(item => item.id === id)
  if (findId == -1) return console.error(new Error('未找到id'))
  ruleForm.drvices.splice(findId, 1)
}

// 提交方法
const submit = async () => {
  const valid = await ruleFormRef.value.validate()
  if (!valid) return false

  // 计划配置项 执行月份
  ruleForm.plannedAllocation.executionMonth = monthList.value
    .filter(item => item.isShow)
    .map(item => item.value)
    .join(',')

  // 计划配置项 执行周期
  ruleForm.plannedAllocation.executionCycle = weekList.value
    .filter(item => item.isShow)
    .map(item => item.value)
    .join(',')

  // 计划配置项 执行日期
  ruleForm.plannedAllocation.executionDays = dayList.value
    .filter(item => item.isShow)
    .map(item => item.value)
    .join(',')

  // 执行间隔
  if (ruleForm.plannedAllocation.planType != 3 && !ruleForm.plannedAllocation.executionInterval) {
    proxy.warningMsg('请完善计划配置项内容')
    return false
  }

  // 执行间隔 周期
  if (ruleForm.plannedAllocation.planType == 2 && !weekList.value.some(item => item.isShow)) {
    proxy.warningMsg('请完善计划配置项内容')
    return false
  }

  // 执行间隔 月份
  if (ruleForm.plannedAllocation.planType == 3 && !monthList.value.some(item => item.isShow)) {
    proxy.warningMsg('请完善计划配置项内容')
    return false
  }

  // 执行间隔 日期
  if (ruleForm.plannedAllocation.planType == 3 && !dayList.value.some(item => item.isShow)) {
    proxy.warningMsg('请完善计划配置项内容')
    return false
  }

  // 保养项目
  if (ruleForm.patrolItems?.length < 1) {
    proxy.warningMsg('请完善保养项目内容')
    return false
  }

  // 保养id
  ruleForm.patrolItemIdStr = ruleForm.patrolItems.map(item => item.id).join(',')

  // 设备id
  if (ruleForm.drvices.length < 1) {
    proxy.warningMsg('请至少关联一个设备')
    return false
  }

  ruleForm.equipmentIdStr = ruleForm.drvices.map(item => item.id).join(',')

  return ruleForm
}

// 监听回显
const initData = () => {
  if (props.data?.id) {
    Object.keys(props.data).forEach(itemKey => (ruleForm[itemKey] = props.data[itemKey]))
    ruleForm.plannedAllocation = props.data.plannedAllocationDto

    const executionCycle = ruleForm.plannedAllocation.executionCycleList
    const executionMonthList = ruleForm.plannedAllocation.executionMonthList
    const executionDaysList = ruleForm.plannedAllocation.executionDaysList
    // 月份
    if (Array.isArray(executionMonthList) && executionMonthList.length > 0) {
      executionMonthList.forEach(itemy => {
        monthList.value.forEach(item => {
          if (item.value == itemy) item.isShow = true
        })
      })
    }

    // 日期
    if (Array.isArray(executionDaysList) && executionDaysList.length > 0) {
      executionDaysList.forEach(itemy => {
        dayList.value.forEach(item => {
          if (item.value == itemy) item.isShow = true
        })
      })
    }

    // 周期
    if (Array.isArray(executionCycle) && executionCycle.length > 0) {
      executionCycle.forEach(itemy => {
        weekList.value.forEach(item => {
          if (item.value == itemy) item.isShow = true
        })
      })
    }

    // 保养项目
  }
}

initData()

const selectArr = ref([])
const handleSelectionChanges = rows => {
  selectArr.value = rows
}

const remove = () => {
  if (selectArr.value.length > 0) {
    selectArr.value.forEach(item => {
      const Find = ruleForm.patrolItems.findIndex(itemy => item.id == itemy.id)
      ruleForm.patrolItems.splice(Find, 1)
    })
  } else {
    if (ruleForm.patrolItems?.length < 1) return
    ruleForm.patrolItems.splice(ruleForm.patrolItems.length - 1, 1)
  }
}

// 计算共和
const total = computed(() => {
  let total = 0
  if (Array.isArray(ruleForm.patrolItems) && ruleForm.patrolItems?.length > 0) {
    ruleForm.patrolItems.forEach(item => (total += item.workingHour))
  }
  return total
})
// 导出方法
defineExpose({ submit })
</script>
<template>
  <el-tabs v-model="activeName" type="card" class="demo-tabs" @tab-click="handleClick">
    <el-tab-pane label="计划信息" name="计划信息">
      <el-form inline ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px" status-icon>
        <el-form-item label="计划编号" v-if="props.title != '新增'">
          <el-input clearable v-model="ruleForm.planCode" disabled />
        </el-form-item>
        <el-form-item label="计划名称" prop="planName">
          <el-input clearable v-model="ruleForm.planName" :disabled="props.disabled" placeholder="请填写计划名称" />
        </el-form-item>

        <el-form-item label="计划开始时间" prop="planStartTime">
          <el-date-picker
            :disabled="props.disabled"
            v-model="ruleForm.planStartTime"
            type="date"
            placeholder="请选择计划开始时间"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="计划结束时间" prop="planEndTime">
          <el-date-picker
            :disabled="props.disabled"
            v-model="ruleForm.planEndTime"
            type="date"
            placeholder="请选择计划结束时间"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <div class="rk">
          <el-form-item label="计划配置项" prop="name">
            <div class="box">
              <div class="config">
                <label class="labelClass">计划类型:</label>
                <el-radio-group :disabled="props.disabled" v-model="ruleForm.plannedAllocation.planType" class="option">
                  <el-radio :label="1" size="large">日</el-radio>
                  <el-radio :label="2" size="large">周</el-radio>
                  <el-radio :label="3" size="large">月</el-radio>
                </el-radio-group>
              </div>

              <!-- 天 -->
              <div class="day" v-if="ruleForm.plannedAllocation.planType == 1">
                <label class="labelClass">执行间隔:</label>
                <el-input
                  type="number"
                  clearable
                  min="0"
                  :disabled="props.disabled"
                  v-model="ruleForm.plannedAllocation.executionInterval"
                  placeholder="单行输入"
                  oninput="if(value){value=value.replace(/[^\d]/g,'')} if(value<0){value=''} if(value>999999999){value=999999999}"
                />
                <span> &nbsp;&nbsp;天</span>
              </div>
              <!-- 周 -->
              <div class="week" v-if="ruleForm.plannedAllocation.planType == 2">
                <div class="flex">
                  <label class="labelClass">执行间隔:</label>
                  <el-input
                    type="number"
                    clearable
                    min="0"
                    :disabled="props.disabled"
                    v-model="ruleForm.plannedAllocation.executionInterval"
                    placeholder="单行输入"
                    oninput="if(value){value=value.replace(/[^\d]/g,'')} if(value<0){value=''} if(value>999999999){value=999999999}"
                  />
                  <span>周</span>
                </div>
                <div class="flex">
                  <label class="labelClass">执行周期:</label>
                  <div class="wrap">
                    <el-checkbox
                      v-for="item in weekList"
                      :disabled="props.disabled"
                      v-model="item.isShow"
                      :label="item.label"
                    />
                  </div>
                </div>
              </div>
              <!-- 月 -->
              <div class="month" v-if="ruleForm.plannedAllocation.planType == 3">
                <div class="flex">
                  <label class="labelClass">执行月份:</label>
                  <div class="wrap">
                    <el-checkbox
                      class="month-checkbox"
                      v-for="item in monthList"
                      :disabled="props.disabled"
                      v-model="item.isShow"
                      :label="item.label"
                    />
                  </div>
                </div>
                <div class="flex">
                  <label class="labelClass">执行日期:</label>
                  <div class="month-days wrap">
                    <el-checkbox
                      class="month-checkbox"
                      v-for="item in dayList"
                      :disabled="props.disabled"
                      v-model="item.isShow"
                      :label="item.label + '号'"
                    />
                  </div>
                </div>
              </div>
            </div>
          </el-form-item>
        </div>
      </el-form>
      <div class="title">点检项目</div>
      <div class="caozuo mb10 flex" v-if="!props.disabled">
        <el-tooltip class="box-item" effect="dark" content="添加" placement="top-start">
          <el-icon @click="projectShow = true"><Plus /></el-icon>
        </el-tooltip>
        <div style="margin: 0 10px"></div>
        <el-tooltip class="box-item" effect="dark" content="勾选删除" placement="top-start">
          <el-icon @click="remove"><Minus /></el-icon>
        </el-tooltip>
      </div>
      <el-table
        stripe
        border
        :data="ruleForm.patrolItems"
        highlight-current-row
        @selection-change="handleSelectionChanges"
      >
        <el-table-column label="序号" width="80" type="index" />
        <el-table-column width="80" v-if="props.bdb">
          <template #default="scope">
            <el-radio-group v-model="handleSelect.id">
              <el-radio :label="scope.row.id" size="large">&nbsp;</el-radio>
            </el-radio-group>
          </template>
        </el-table-column>
        <el-table-column v-else type="selection" width="55" align="center" fixed="left" />
        <el-table-column label="项目编号" prop="patrolItemCode" width="auto" align="center" show-overflow-tooltip />
        <el-table-column label="项目名称" prop="patrolItemName" width="auto" align="center" show-overflow-tooltip />
        <el-table-column label="巡检内容" prop="patrolItemContent" width="auto" align="center" show-overflow-tooltip />
        <el-table-column label="检验标准" prop="inspectionStandard" width="auto" align="center" show-overflow-tooltip />
        <el-table-column label="检验类型" prop="inspectionTypeDict" width="auto" align="center" show-overflow-tooltip>
        </el-table-column>
        <el-table-column label="判定结果项" prop="decisionResult" width="auto" align="center" show-overflow-tooltip />
        <el-table-column label="标准工时" prop="workingHour" width="auto" align="center" show-overflow-tooltip />
        <el-table-column label="备注" prop="remark" width="auto" align="center" show-overflow-tooltip />
      </el-table>
      <div class="total">
        总工时：
        {{ total }}
      </div>
    </el-tab-pane>
    <el-tab-pane label="关联设备" name="关联设备">
      <div class="caozuo" v-if="!props.disabled">
        <el-button class="mb10" @click="deviceShow = true"> 关联设备</el-button>
      </div>
      <el-table stripe border :data="ruleForm.drvices" highlight-current-row>
        <el-table-column label="序号" width="80" type="index" />
        <el-table-column label="设备名称" prop="deviceName" width="auto" show-overflow-tooltip />
        <el-table-column label="设备编码" prop="deviceCode" width="auto" show-overflow-tooltip />
        <el-table-column label="设备类型" prop="deviceType" width="auto" show-overflow-tooltip />
        <el-table-column label="设备型号" prop="deviceUnitType" width="auto" show-overflow-tooltip />
        <el-table-column label="设备位置" prop="installationLocation" width="auto" show-overflow-tooltip />
        <el-table-column label="操作" width="220" align="center" fixed="right" v-if="!props.disabled">
          <template #default="scope">
            <div>
              <el-link
                type="primary"
                v-hasPermi="['device:maintenance:plan:edit']"
                text="解除关联"
                @click="removeDevice(scope.row.id)"
              />
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-tab-pane>
  </el-tabs>
  <!-- 保养项目 -->
  <Project :bdb="false" :is-show="projectShow" @preservation="addProject" @cancel="projectShow = false" />
  <!-- 设备列表 -->
  <Device :bdb="false" :is-show="deviceShow" @preservation="addDevice" @cancel="deviceShow = false" />
</template>

<style lang="scss" scoped>
.rk ::v-deep .el-form-item {
  width: 100% !important;
}

.box {
  height: 180px;
  overflow: auto;
  & .labelClass {
    width: 120px !important;
  }
}
.config {
  display: flex;
  align-items: center;
  margin-top: 20px;
}

.day {
  display: flex;
  align-items: center;
}

.day ::v-deep .el-input {
  width: 150px !important;
}
.week ::v-deep .el-input {
  width: 150px !important;
}

.month ::v-deep .el-input {
  width: 150px !important;
}

.month-days {
  flex-wrap: wrap;
}
.month-checkbox {
  width: 50px;
}
.wrap {
  width: 100%;
  flex-wrap: wrap;
}

.caozuo {
  float: right;
  cursor: pointer;
}

.total {
  float: right;
  font-size: 16px;
  margin-top: 15px;
  margin-right: 15px;
}
</style>
